package fr.generali.poc.statemachine.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import statemachine.poc.generali.fr.statemachine_dto.DossierDTO;
import statemachine.poc.generali.fr.statemachine_service_wsdl.DossierServicePortType;
import fr.generali.poc.statemachine.choregraphe.IChoregraphe;
import fr.generali.poc.statemachine.events.Event;
import fr.generali.poc.statemachine.model.Dossier;
import fr.generali.poc.statemachine.states.StateAbstract;
import fr.generali.poc.statemachine.states.StateEnum;

public class DossierServiceImpl implements DossierServicePortType {

	private IChoregraphe choregraphe;

	public void setChoregraphe(IChoregraphe choregraphe) {
		this.choregraphe = choregraphe;
	}

	@Override
	public DossierDTO validerDossier(DossierDTO dossier, String event) {
		Dossier vDossier = new Dossier();
		vDossier.setId(dossier.getId());
		vDossier.setDonnees(dossier.getDonnees());
		vDossier.setStatut(getStatutForName(dossier.getStatut()));
		vDossier = choregraphe.execute(vDossier, getEventForName(event));
		DossierDTO vDossierDTO = new DossierDTO();
		vDossierDTO.setId(vDossier.getId());
		vDossierDTO.setDonnees(vDossier.getDonnees());
		vDossierDTO.setStatut(vDossier.getStatut().getNAME());
		return vDossierDTO;
	}

	private StateAbstract getStatutForName(String state) {
		StateEnum stateE = StateEnum.valueOf((state));
		if (stateE == null) {
			throw new IllegalArgumentException("le statut " + state
					+ " est inconnu");
		}
		return stateE.getState();
	}

	private Event getEventForName(String pEvent) {
		Event vEvent = Event.valueOf(pEvent);
		if (vEvent == null) {
			throw new IllegalArgumentException("l evt " + pEvent
					+ " n est pas autorise");
		}
		return vEvent;
	}

}
